import { Context, BaseService } from '../Service'
import { ServiceNo } from '../ServiceNo'
import { isDevMod } from '../../config'
import { User, UserType } from '../../model'
import { encryptPassword } from '../../util/securityUtil'

class UserService extends BaseService {
  getUserInfo (ctx: Context) {
    ctx.body = {
      username: ctx.user.username,
      email: ctx.user.email,
      createTime: ctx.user.createTime
    }
  }

  init () {
    let methodNo = 100
    this.addServiceInterface({
      methodNo: `${methodNo++}`,
      method: this.getUserInfo,
      methodDesc: '获取用户信息接口'
    })

    if (isDevMod()) {
      this.insertDefaultUser()
    }
  }

  async insertDefaultUser () {
    const username = 'lenchu'
    const userableUserTablePostFix = await this.findUseableUserTablePostFix(username)

    const userDoc: UserType = {
      username,
      password: encryptPassword('lenchu'),
      email: '0@lenchu.cn',
      versionTable: `version${userableUserTablePostFix}`,
      accountTable: `account${userableUserTablePostFix}`
    }
    const user = await User.findOne({
      username
    }).select('username')
    if (!user) {
      new User(userDoc).save()
    }
  }

  /**
   * version account 按用户分表，不同用户数据存在不同表中
   * 需要根据用户名来区分不同用户的表
   * 此方法用于获取可用的表名，因为不同用户的表名不能冲突
   * @param username username
   */
  async findUseableUserTablePostFix (username: string) {
    let i = 1000
    let mayUser
    do {
      mayUser = await User.findOne({
        versionTable: `version_${username}_${i}`,
        accountTable: `account_${username}_${i}`
      })
    } while (mayUser && i++)
    return `_${username}_${i}`
  }
}

export default new UserService(ServiceNo.user)
